<template>
  <el-card class="box-card">
    <el-row :gutter="10">
      <el-col :span="2">
        <el-select
          v-model="qtypeId"
          placeholder="请选择分类"
          size="medium"
          style="width: 180px"
          @change="selectDepartment"
        >
          <el-option
            v-for="item in qtypeData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-col>

      <el-col :span="6">
        <el-input v-model="topic" placeholder="请输入关键词"></el-input>
      </el-col>
      <div class="btn">
        <el-button
          type="info"
          @click="
            type = null;
            qtypeId = null;
            topic = null;
          "
          >重置</el-button
        >
        <el-button type="primary" @click="listByPage()">查询</el-button>
        <el-button
          type="success"
          @click="
            clearForm();
            title = '新增考题';
            drawer = true;
          "
          >新增</el-button
        >
      </div>
    </el-row>
  </el-card>

  <el-card class="box-card2">
    <el-table :data="questionData" style="width: 100%">
      <el-table-column align="center" fixed prop="id" label="序号"> </el-table-column>
      <el-table-column align="center" fixed width="150" label="题目" #default="{ row }">
        <el-popover
          placement="top-start"
          title="题目："
          :width="200"
          trigger="hover"
          :content="row.topic"
        >
          <template #reference>
            <el-button class="m-2">{{ row.topic.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="a" width="150" label="A" #default="{ row }">
        <el-popover
          placement="top-start"
          title="选项A："
          :width="200"
          trigger="hover"
          :content="row.a"
        >
          <template #reference>
            <el-button class="m-2">{{ row.a.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="b" width="150" label="B" #default="{ row }">
        <el-popover
          placement="top-start"
          title="选项B："
          :width="200"
          trigger="hover"
          :content="row.b"
        >
          <template #reference>
            <el-button class="m-2">{{ row.b.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="c" width="150" label="C" #default="{ row }">
        <el-popover
          placement="top-start"
          title="选项C："
          :width="200"
          trigger="hover"
          :content="row.c"
        >
          <template #reference>
            <el-button class="m-2">{{ row.c.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="d" width="150" label="D" #default="{ row }">
        <el-popover
          placement="top-start"
          title="选项D："
          :width="200"
          trigger="hover"
          :content="row.d"
        >
          <template #reference>
            <el-button class="m-2">{{ row.d.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="e" width="150" label="E" #default="{ row }">
        <el-popover
          placement="top-start"
          title="选项E："
          :width="200"
          trigger="hover"
          :content="row.e"
        >
          <template #reference>
            <el-button class="m-2">{{ row.e.slice(0, 7) }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <el-table-column align="center" prop="answer" label="答案"> </el-table-column>

      <el-table-column align="center" prop="type" label="题型"> </el-table-column>

      <el-table-column align="center" prop="qtypeId" label="分类"> </el-table-column>

      <el-table-column align="center" prop="analysis" label="解析" #default="{ row }"
        ><el-popover
          placement="top-start"
          title="解析："
          :width="200"
          trigger="hover"
          :content="row.analysis"
        >
          <template #reference>
            <el-button class="m-2">{{
              row.analysis ? row.analysis.slice(0, 7) : "暂无解析"
            }}</el-button>
          </template>
        </el-popover>
      </el-table-column>

      <!-- <el-table-column align="center" prop="pic" label="图片" #default="{ row }">
        <el-popover
          placement="top-start"
          title="图片："
          :width="200"
          trigger="hover"
          :content="row.pic"
        >
          <template #reference>
            <el-button class="m-2">查看图片</el-button>
          </template>
        </el-popover>
      </el-table-column> -->

      <el-table-column label="操作" fixed="right" width="120" align="center">
        <template #default="{ row }">
          <!-- 修改 -->
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="
              title = '修改考题';
              getById(row.id);
              drawer = true;
            "
          />

          <el-popconfirm
            title="确定要删除该数据吗？"
            @cancel="ElMessage('您取消了删除')"
            @confirm="deleteById(row.id)"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" circle />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-pagination
      class="fenye"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[2, 4, 6, 8]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>

  <!-- 抽屉表单 -->
  <el-drawer v-model="drawer" :title="title" :with-header="false">
    <div>{{ title }}</div>
    <el-form :model="questionForm" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="考题题目：" prop="topic">
        <el-input v-model="questionForm.topic" placeholder="请输入题目"></el-input>
      </el-form-item>
      <el-form-item label="考题分类：" prop="qtypeId">
        <el-select placeholder="请选择" v-model="questionForm.qtypeId">
          <el-option
            v-for="t in qtypeData"
            :key="t.id"
            :label="t.name"
            :value="t.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="A:" prop="a">
        <el-input v-model="questionForm.a" placeholder="请输入选项内容"></el-input>
      </el-form-item>
      <el-form-item label="B:" prop="b">
        <el-input v-model="questionForm.b" placeholder="请输入选项内容"></el-input>
      </el-form-item>
      <el-form-item label="C:" prop="c">
        <el-input v-model="questionForm.c" placeholder="请输入选项内容"></el-input>
      </el-form-item>
      <el-form-item label="D:" prop="d">
        <el-input v-model="questionForm.d" placeholder="请输入选项内容"></el-input>
      </el-form-item>
      <el-form-item label="E:" prop="e">
        <el-input v-model="questionForm.e" placeholder="请输入选项内容"></el-input>
      </el-form-item>
      <el-form-item label="题型：" prop="type">
        <el-radio-group v-model="questionForm.type" size="large">
          <el-radio-button label="单选题" value="0" />
          <el-radio-button label="多选题" value="1" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="答案：" prop="answer">
        <el-select
          v-model="questionForm.answer"
          :multiple="questionForm.type == 1"
          placeholder="请选择选择答案"
          style="width: 240px"
        >
          <el-option
            v-for="(item, index) in ['A', 'B', 'C', 'D', 'E']"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="解析：" prop="analysis">
        <el-input v-model="questionForm.analysis" placeholder="请输入解析内容"></el-input>
      </el-form-item>
      <el-form-item label="插图：">
        <el-upload
          class="avatar-uploader"
          :auto-upload="true"
          :show-file-list="false"
          action="http://localhost:8080/user/uploadAvatar"
          name="file"
          :on-success="uploadsuccess"
        >
          <img v-if="questionForm.pic" :src="questionForm.pic" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="title == '修改考题' ? edit() : insert()">{{
          title == "修改考题" ? "修改" : "新增"
        }}</el-button>
        <el-button type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { Check, Delete, Edit, Message, Search, Star } from "@element-plus/icons-vue";
import {
  questionDeleteByIdService,
  questionEditService,
  questionGetByIdService,
  questionInsertService,
  questionListByPageService,
  questionTypeListService,
} from "@/api/answer";
import { ref } from "vue";
import { ElMessage } from "element-plus";

const pageNum = ref(1);
const pageSize = ref(8);
const total = ref(100);

const topic = ref();
const type = ref();
const qtypeId = ref(); //考题分类id

const questionData = ref([]); //考题集合
const qtypeData = ref([]); //分类集合

const title = ref();
const drawer = ref(false);
//考题表单模型
const questionForm = ref({
  topic: "",
  a: "",
  b: "",
  c: "",
  d: "",
  e: "",
  type: "",
  answer: [], // 确保 `answer` 是一个数组
  analysis: "",
  pic: "",
  qtypeId: "",
});

//清空表单
const clearForm = () => {
  //清空规则状态
  if (formRef.value) formRef.value.resetFields();

  questionForm.value = {
    topic: "",
    a: "",
    b: "",
    c: "",
    d: "",
    e: "",
    type: "",
    answer: [], // 确保 `answer` 是一个数组
    analysis: "",
    pic: "",
    qtypeId: "",
  };
};

const rules = {
  topic: [{ required: true, message: "请输入题目", trigger: "blur" }],
  qtypeId: [{ required: true, message: "请选择考题分类", trigger: "change" }],
  a: [{ required: true, message: "请至少设置两个选择", trigger: "blur" }],
  b: [{ required: true, message: "请至少设置两个选择", trigger: "blur" }],
  answer: [{ required: true, message: "请选择答案", trigger: "change" }],
  analysis: [{ required: true, message: "请输入解析内容", trigger: "blur" }],
};

const formRef = ref();

//分页获取考题详情
const listByPage = async () => {
  const data = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    topic: topic.value ? topic.value : null,
    type: type.value ? type.value : null,
    qtypeId: qtypeId.value ? qtypeId.value : null,
  };
  //获取考题
  let result1 = await questionListByPageService(data);
  questionData.value = result1.data.data.items;
  total.value = result1.data.data.total;
  console.log("分页获取考题详情Api", questionData.value);
  //获取分类
  let result2 = await questionTypeListService();
  qtypeData.value = result2.data.data;
  console.log("分类集合API", qtypeData.value);

  //处理数据
  for (let i = 0; i < questionData.value.length; i++) {
    if (questionData.value[i].type == 0) {
      questionData.value[i].type = "单选题";
    } else {
      questionData.value[i].type = "多选题";
    }
    questionData.value[i].pic ? true : (questionData.value[i].pic = "暂无图片");

    let found = false;
    for (let j = 0; j < qtypeData.value.length; j++) {
      if (questionData.value[i].qtypeId == qtypeData.value[j].id) {
        questionData.value[i].qtypeId = qtypeData.value[j].name;
        found = true;
        break; // 找到匹配项后可以跳出内层循环
      }
    }

    if (!found) {
      questionData.value[i].qtypeId = "暂无分类";
    }
  }
};
listByPage();

const handleCurrentChange = (num) => {
  //页数改变触发函数
  pageNum.value = num;
  listByPage();
};

//图片上传成功的回调函数
const uploadsuccess = (result) => {
  questionForm.value.pic = result.data;
  console.log(questionForm.value.pic);
};
//通过id获取考题信息函数
const getById = async (id) => {
  let result = await questionGetByIdService(id);
  questionForm.value = result.data.data;
  console.log(questionForm.value);
};
getById(1);
//修改考题信息函数
const edit = () => {
  formRef.value.validate(async (v) => {
    if (v) {
      if (questionForm.value.type == 1) {
        // 使用 === 进行比较
        questionForm.value.answer = questionForm.value.answer.join("");
      }

      console.log(questionForm.value);
      let result = await questionEditService(questionForm.value);
      ElMessage.success(result.data.data);

      drawer.value = false;
      listByPage();
    } else {
      ElMessage.error("请检查填写是否规范");
    }
  });
};
//新增考题信息函数
const insert = async () => {
  formRef.value.validate(async (v) => {
    if (v) {
      if (questionForm.value.type == 1) {
        // 使用 === 进行比较
        questionForm.value.answer = questionForm.value.answer.join("");
      }

      let result = await questionInsertService(questionForm.value);
      ElMessage.success(result.data.data);

      drawer.value = false;
      listByPage();
    } else {
      ElMessage.error("请检查填写是否规范");
      return;
    }
  });
};
const deleteById = async (id) => {
  let result = await questionDeleteByIdService(id);
  ElMessage.success(result.data.data);

  listByPage();
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
    }
  }
}
.m-2 {
  border: none;
}

.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.hd {
  height: 100px;
  background-color: #fff;
  margin-top: 15px;
  box-shadow: 0 -0.05333333rem 0.42666667rem 0 rgba(14, 86, 127, 0.09);
}

.box-card {
  margin-top: 15px;
}

.btn {
  margin-left: 20px;
}

.box-card2 {
  margin-top: 15px;
  height: 525px;
}

.fenye {
  margin-top: 30px;
  margin-left: 33%;
}

.ccc {
  width: 400px;

  margin: 10px auto;
  /*background-color: skyblue;*/
}

.preview {
  width: 95%;
}

.myprogress {
  margin-left: 50px;
}
</style>
